<template>
<div class="cart"> 
  <!-- 顶部导航 -->
  <van-nav-bar
    left-text="购物车"
    left-arrow
    @click-left="onClickLeft"
    class="top-nav-bar"
  >
      <template #right>
       <van-cell is-link @click="showPopup" >编辑地址</van-cell>
          <van-popup v-model="show">
            <van-address-edit
              :area-list="areaList"
              show-postal
              show-delete
              show-set-default
              show-search-result
              :search-result="searchResult"
              :area-columns-placeholder="['请选择', '请选择', '请选择']"
              @save="onSave"
              @delete="onDelete"
              @change-detail="onChangeDetail"
            />
          </van-popup>
      </template>
  </van-nav-bar>
   <!-- 购物车商品列表 -->
   <div class="cart-main-list">
     <van-swipe-cell  v-for="i in carts"  :key="i.id" class="shoplist" >
        <van-card
          :num="i.amount"
          :price="i.product.price"
          :title="i.product.name"
          :thumb="i.product.coverImage | dalImg"
          
          
         
        >
          <template #tag>
            <van-checkbox v-model="i.checked"/>
          </template>
          <template #footer>
            <van-stepper v-model="i.amount" theme="round" button-size="22" disable-input @plus="addShop(i)" @minus="reduceShop(i)"/>
          </template>
        </van-card>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="deleteShop(i)"/>
        </template>
      </van-swipe-cell>
   </div> 
   <!-- 推荐 -->
   <h2 class="cart-new-h2">为你推荐</h2>
   <div>
     <!-- 加载更多 -->
       <!-- loading表示是否正在加载，
       finished 当数据加载完成后设置为true
       @load是方法，，“滚动条触底时候触发” -->
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          class="cart-mian-new"
        >
          <van-cell v-for="item in list" :key="item" :title="item" />
         <van-card
            :num="newShop.amount"
            tag="标签"
            :price="newShop.price.toFixed(2)"
            :title="newShop.name"
            :thumb="newShop.coverImage"
            :origin-price="newShop.price"
            v-for="newShop in products"
            :key="Math.random()*10+newShop"
            @click-thumb ="toDetail(newShop.id)"
            @click="toDetail(newShop.id)"
            class="new-shop"
          />
        </van-list>
      
    
   </div>
  <!-- 去结算 -->
  <van-submit-bar :price="sumPrice" button-text="提交订单" @submit="onSubmit">
    <van-checkbox v-model="checked">全选</van-checkbox>
  </van-submit-bar>
</div>
 
</template>

<script>

import { Toast } from 'vant';
import { areaList } from '@vant/area-data';
import {loadProductsAPI} from "../services/products"
import {loadCartsAPI,addToCartAPI,deleteCartAPI}from "../services/carts"
import {submitOrderAPI} from "../services/order"

export default {
    data() {
    return {
      carts:[],
      value:1,
      show:false,
      areaList,
      searchResult: [],
      //商品加载更多
      products:[],
      page:3,
      list: [],
      loading: false,
      finished: false,
      shopDisplay:true,
      //订单
      checkedProducts:[],
      receiver:"小黑",
      address:"天使街",
    };
  },
  // 创建完成
  created(){
    this.onLoad();
    this.loadData();
  },
   methods: {
     // 加载数据
     async loadData(){
       const res = await loadCartsAPI();
       console.log(res);
       this.carts=res.data.filter((item)=>item.product).map((item)=>({
         ...item,
         checked:false,
       }));
     },
    //  返回按钮
    onClickLeft() {
      this.$router.push({
        name:"Home"
      })
    },
    //步进器加减
    async addShop(item){
      await addToCartAPI(item.product.id,1,item.product.price);
    },
    async reduceShop(item){
      await addToCartAPI(item.product.id,-1,item.product.price);
    },
    // 删除数据
    async deleteShop(item){
     await deleteCartAPI(item.id);
     this.loadData();
    },
    // 提交订单
    async onSubmit(){
      this.checkedProducts.push(this.carts.filter(item=>item.checked))
      console.log(this.checkedProducts)
      await submitOrderAPI(this.checkedProducts,this.receiver,this.address)
      this.$router.push({
        name:"Order",
      })
    },
    // 地址弹出层
     showPopup() {
      this.show = true;
    },
    // 地址
    onSave() {
      Toast('save');
    },
    onDelete() {
      Toast('delete');
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: '黄龙万科中心',
            address: '杭州市西湖区',
          },
        ];
      } else {
        this.searchResult = [];
      }
    },
    // 加载更多 解决异步
    async loadMore(){
      this.loading= true;//设置加载中，不触发onload
      const res = await loadProductsAPI(this.page);
      if(res.data.length==0){
        this.finished = true;//返回数据长度为零，加载结束
      }
      this.page++;
      // 扩展符
      this.products.push(...res.data);
      this.loading=false;// 加载结束
    },
    onLoad(){
      this.loadMore();
    },
    // 推荐跳转详情
    toDetail(id){
      this.$router.push({
        name:"Detail",
        query:{
          id,
        }
      })
    },
  },
  //计算属性
  computed:{
    checked:{
      //全选与反选
      set(v){
        this.carts.forEach(item=>item.checked=v)
      },
      // 
      get(){
        return this.carts.every((item=>item.checked))
      }
    },
    sumPrice(){
      return this.carts.filter(item=>item.checked).reduce((pre,cur)=>pre+cur.amount*cur.price*100,0)
    }
  },
 
}
</script>

<style>
/* navbar */
.van-nav-bar__content{
  height: 60px;
  
}
 /* 顶部导肮固定 */
.top-nav-bar{
  position:sticky;
  top:0;
  z-index:3;
}

.delete-button {
	height: 100%;
}

  /* 角标位置 */
  .shoplist{
    position: relative;
  }
  .van-card__tag{
    position: absolute;
    top: -3px;
    left: -10px;
  }
  /* 推荐 */
  .cart-new-h2{
    display: block;
    width: 100%;
    text-align: center;
  }
  .cart-mian-new{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }
  .new-shop{
    width: 45%;
    height: 200px;
    box-sizing: border-box;
  }
  .van-card:first-child{
    margin-top: 8px;
  }
  
</style>
